package com.ebo.synframework.nettybase.codec;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import com.google.protobuf.GeneratedMessageV3;
import net.sf.cglib.reflect.FastClass;
import net.sf.cglib.reflect.FastMethod;
import com.google.protobuf.GeneratedMessage;

public class ProtoFactory {
	
	private static Map<String, GeneratedMessageV3> allProtos = new HashMap<String, GeneratedMessageV3>();
	
	public static void init(String packageName) {
		Set<Class<?>> classList = ProtoUtil.getClasses(packageName);
		for(Class<?> clazz : classList) {
			if(com.google.protobuf.GeneratedMessageV3.class.isAssignableFrom(clazz)) {
				FastClass fastClass = FastClass.create(clazz);
	            FastMethod method = fastClass.getMethod("getDefaultInstance", null);
	            try {
					GeneratedMessageV3 proto = (GeneratedMessageV3) method.invoke(null, null);
					allProtos.put(clazz.getSimpleName(), proto);
				} catch (InvocationTargetException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public static final GeneratedMessageV3 getProtoInstance(String name) {
		return allProtos.get(name);
	}
	
}
